package com.etlmaster.executor.steps.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;

import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.StepState;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
@StepInstruction("buildCube")
public class CallKylinBuildCubeServiceStep extends Step {

	private CallKylinBuildCubeServiceStepMeta meta;

	public CallKylinBuildCubeServiceStep(StepMeta meta) {
		super(meta);
		this.meta = (CallKylinBuildCubeServiceStepMeta) meta;
	}

	@Override
	protected int handle() {
		String path = DataCollectionUtils.getProperties("kylin_address")+meta.getCubeName()+"/rebuild";
		try {
			String result=put(
					path,
			        "{\"startTime\": "+System.currentTimeMillis()+",\"endTime\": "+System.currentTimeMillis()+10000+",\"buildType\": \"BUILD\"}");
			meta.getStepState().getReturnValue().put("kylin_rtn", result);
			meta.log("INFO",result);
		} catch (IOException e) {
			e.printStackTrace();
			meta.log("ERROR","调用kylin服务失败!");
			return StepState.RUNNING_FAILED;
		}
		return StepState.RUNNING_SUCCESSED;
	}

	@Override
	public boolean stop() {
		
		return false;
	}

	public String put(String addr, String params) throws IOException {
		String result = "";
		URL url = new URL(addr);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("PUT");
		connection.setDoOutput(true);
		String auth = DataCollectionUtils.getProperties("kylin_account") + ":"
				+ DataCollectionUtils.getProperties("kylin_password");
		String code = new String(new Base64().encode(auth.getBytes()));
		connection.setRequestProperty("Authorization", "Basic " + code);
		connection.setRequestProperty("Content-Type",
				"application/json;charset=UTF-8");
		PrintWriter out = new PrintWriter(connection.getOutputStream());
		out.write(params);
		out.close();
		BufferedReader in;
		in = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));

		StringBuffer response = new StringBuffer();
		String line;
		while ((line = in.readLine()) != null)
			response.append(line + "\n");
		in.close();

		result = response.toString();

		return result;
	}
}
